﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Animaonline.Weather;
using Animaonline.Weather.WeatherData;
using Core.BOL;
using Core.DAL;
using Core.Extentions;

namespace ScoutNET.Controllers
{
    public class MailController : Controller
    {
        #region Repositories
        private CalendarRepository cr = new CalendarRepository();
        private StaffRepository str = new StaffRepository();
        private SectionRepository ser = new SectionRepository();
        private ConvocRepository cor = new ConvocRepository();
        private StatMailsRepository smr = new StatMailsRepository();
        private MailToGenerateRepository mtgr = new MailToGenerateRepository();
        private NewsRepository nr = new NewsRepository();
        private AlbumsRepository ar = new AlbumsRepository();
        private MyAlbumRepository mar = new MyAlbumRepository();
        #endregion

        public ActionResult News(string systemName, int mailId, Guid userId)
        {
            //Data
            MembershipUser mu = Membership.GetUser(userId);
            tMail_ToGenerate t = mtgr.GetMailById(mailId);

            ViewData["MailUrl"] = Url.Action("News", new { controller = "Mail", systemName = systemName, mailId = mailId, userId = userId });

            if (mu != null && t != null)
            {
                tSite_Section s = ser.GetSectionsBySystemName(systemName);
                tSite_New n = nr.GetNewsByID((int)t.ItemID);

                ViewData["UserLogin"] = mu.UserName;
                ViewData["UserID"] = ((Guid)mu.ProviderUserKey).ToString();
                ViewData["SectionName"] = s.Section;
                ViewData["CopyrightDate"] = DateTime.Now.GetNowTimeByTimeZone().Year;
                ViewData["SiteName"] = ConfigurationManager.AppSettings["SiteName"];
                ViewData["CampaignName"] = this.Server.UrlEncode(n.Title);
                ViewData["MailID"] = t.MID;

                return View(n);
            }
            else
            {
                string[] saBreadcrumb = new String[2];
                saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
                saBreadcrumb[1] = Resources.Mail_Agenda_Error_Breadcrumb;
                ViewData["Breadcrumb"] = saBreadcrumb;

                ViewData["PageTitle"] = Resources.Mail_Agenda_Error_Title;
                ViewData["ErrorMessage"] = Resources.Mail_Agenda_Error;

                if (this.ControllerContext.HttpContext.Request.Headers["ScheduleTask"] != null)
                {
                    this.ControllerContext.HttpContext.Response.StatusCode = 204;
                }
                return View("Error");
            }
        }

        public ActionResult Convoc(string systemName, int mailId, Guid userId)
        {
            MembershipUser mu = Membership.GetUser(userId);
            tMail_ToGenerate t = mtgr.GetMailById(mailId);
            tSite_Convoc c = cor.GetConvocByID((int)t.ItemID);
            tSite_New n = (c != null && c.NID != null) ? nr.GetNewsByID((int)c.NID) : null;

            ViewData["MailUrl"] = Url.Action("Convoc", new { controller = "Mail", systemName = systemName, mailId = mailId, userId = userId });

            if (mu != null && t != null && c != null && n != null)
            {
                tSite_Section s = ser.GetSectionsBySystemName(systemName);

                string convocUrl = Url.Action("Detail", new { controller = "Convoc", SystemName = s.SystemName.UppercaseFirst(), ID = c.ID, utm_source = "mail", utm_medium = "ContentLink", utm_campaign = this.Server.UrlEncode(n.Title) });

                ViewData["UserLogin"] = mu.UserName;
                ViewData["UserID"] = ((Guid)mu.ProviderUserKey).ToString();
                ViewData["SectionName"] = s.Section;
                ViewData["CopyrightDate"] = DateTime.Now.GetNowTimeByTimeZone().Year;
                ViewData["SiteName"] = ConfigurationManager.AppSettings["SiteName"];
                ViewData["CampaignName"] = this.Server.UrlEncode(n.Title);
                ViewData["MailID"] = t.MID;
                ViewData["MailContent"] = Resources.ResourceManager.GetString("Convoc_Create_NewsText" + t.ResourceID).Replace("[INSERT_DATE]", n.InsertDate.ToString("dd/MM/yyyy")).Replace("[SECTION]", s.Sections.ToLower()).Replace("[CONVOC_LINK]", convocUrl);

                return View(n);
            }
            else
            {
                string[] saBreadcrumb = new String[2];
                saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
                saBreadcrumb[1] = Resources.Mail_Agenda_Error_Breadcrumb;
                ViewData["Breadcrumb"] = saBreadcrumb;

                ViewData["PageTitle"] = Resources.Mail_Agenda_Error_Title;
                ViewData["ErrorMessage"] = Resources.Mail_Agenda_Error;

                if (this.ControllerContext.HttpContext.Request.Headers["ScheduleTask"] != null)
                {
                    this.ControllerContext.HttpContext.Response.StatusCode = 204;
                }
                return View("Error");
            }
        }

        public ActionResult Album(string systemName, int mailId, Guid userId)
        {
            MembershipUser mu = Membership.GetUser(userId);
            tMail_ToGenerate t = mtgr.GetMailById(mailId);

            ViewData["MailUrl"] = Url.Action("Album", new { controller = "Mail", systemName = systemName, mailId = mailId, userId = userId });

            if (mu != null && t != null)
            {
                tSite_Section s = ser.GetSectionsBySystemName(systemName);
                tSite_Photos_Album a = ar.GetAlbumByID((int)t.ItemID);

                string albumUrl = string.Concat("/", a.SystemName.UppercaseFirst() + "/Album/Index/", a.ID, "/", a.Title.ParseUrl());

                ViewData["UserLogin"] = mu.UserName;
                ViewData["UserID"] = ((Guid)mu.ProviderUserKey).ToString();
                ViewData["SectionName"] = s.Section;
                ViewData["CopyrightDate"] = DateTime.Now.GetNowTimeByTimeZone().Year;
                ViewData["SiteName"] = ConfigurationManager.AppSettings["SiteName"];
                ViewData["CampaignName"] = this.Server.UrlEncode(a.Title);
                ViewData["MailID"] = t.MID;
                ViewData["MailContent"] = Resources.ResourceManager.GetString("Album_Validation_Mail" + t.ResourceID).Replace("[ALBUM_TITLE]", a.Title).Replace("[DESCRIPTION]", a.Description).Replace("[SECTION_NAME]", systemName.ToLower()).Replace("[ALBUM_URL]", albumUrl).Replace("[CAMPAIGN_NAME]", ViewData["CampaignName"].ToString());

                return View(a);
            }
            else
            {
                string[] saBreadcrumb = new String[2];
                saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
                saBreadcrumb[1] = Resources.Mail_Agenda_Error_Breadcrumb;
                ViewData["Breadcrumb"] = saBreadcrumb;

                ViewData["PageTitle"] = Resources.Mail_Agenda_Error_Title;
                ViewData["ErrorMessage"] = Resources.Mail_Agenda_Error;

                if (this.ControllerContext.HttpContext.Request.Headers["ScheduleTask"] != null)
                {
                    this.ControllerContext.HttpContext.Response.StatusCode = 204;
                }
                return View("Error");
            }
        }

        public ActionResult DownloadAlbum(string systemName, Guid userId, int mailId)
        {
            MembershipUser mu = Membership.GetUser(userId);
            tSite_Photos_Album al = ar.GetAlbumByID(mailId);
            tSite_Section s = ser.GetSectionsBySystemName(systemName);

            if (al != null && mu != null && s != null)
            {
                string tempFolder = ConfigurationManager.AppSettings["TempPath"];
                string zipFileUrl = tempFolder + userId.ToString() + "_" + al.ID.ToString("D6") + ".zip";

                ViewData["ZipFileUrl"] = zipFileUrl;
                ViewData["AlbumName"] = al.Title;
                ViewData["PageTitle"] = Resources.Mail_DownloadAlbum_MailTitle.Replace("[TITLE]", al.Title);
                ViewData["UserLogin"] = mu.UserName;
                ViewData["UserID"] = ((Guid)mu.ProviderUserKey).ToString();
                ViewData["SectionName"] = s.Section;
                ViewData["CopyrightDate"] = DateTime.Now.GetNowTimeByTimeZone().Year;
                ViewData["SiteName"] = ConfigurationManager.AppSettings["SiteName"];
                ViewData["CampaignName"] = Server.UrlEncode(al.Title);
            }
            else
            {
                string[] saBreadcrumb = new String[2];
                saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
                saBreadcrumb[1] = Resources.Mail_Agenda_Error_Breadcrumb;
                ViewData["Breadcrumb"] = saBreadcrumb;

                ViewData["PageTitle"] = Resources.Mail_Agenda_Error_Title;
                ViewData["ErrorMessage"] = Resources.Mail_Agenda_Error;

                if (this.ControllerContext.HttpContext.Request.Headers["ScheduleTask"] != null)
                {
                    this.ControllerContext.HttpContext.Response.StatusCode = 204;
                }
                return View("Error");
            }

            return View(al);
        }

        public ActionResult DownloadMyAlbum(string systemName, Guid userId)
        {
            MembershipUser mu = Membership.GetUser(userId);
            tSite_Photos_MyAlbum pictureMyAlbum = mar.GetRandImagesByUserID(userId);

            if (mu != null && pictureMyAlbum != null)
            {
                string tempFolder = ConfigurationManager.AppSettings["TempPath"];
                string zipFileUrl = tempFolder + userId.ToString() + ".zip";

                ViewData["ZipFileUrl"] = zipFileUrl;
                ViewData["PageTitle"] = Resources.Mail_DownloadMyAlbum_MailTitle;
                ViewData["UserLogin"] = mu.UserName;
                ViewData["UserID"] = ((Guid)mu.ProviderUserKey).ToString();
                ViewData["CopyrightDate"] = DateTime.Now.GetNowTimeByTimeZone().Year;
                ViewData["SiteName"] = ConfigurationManager.AppSettings["SiteName"];
                ViewData["CampaignName"] = Server.UrlEncode("My Album");
            }
            else
            {
                string[] saBreadcrumb = new String[2];
                saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
                saBreadcrumb[1] = Resources.Mail_Agenda_Error_Breadcrumb;
                ViewData["Breadcrumb"] = saBreadcrumb;

                ViewData["PageTitle"] = Resources.Mail_Agenda_Error_Title;
                ViewData["ErrorMessage"] = Resources.Mail_Agenda_Error;

                if (this.ControllerContext.HttpContext.Request.Headers["ScheduleTask"] != null)
                {
                    this.ControllerContext.HttpContext.Response.StatusCode = 204;
                }
                return View("Error");
            }

            return View(pictureMyAlbum);
        }

        public ActionResult Agenda(string systemName, int mailId, Guid userId)
        {
            tMail_ToGenerate mtg = mtgr.GetMailById(mailId);
            
            MembershipUser mu = Membership.GetUser(userId);

            List<tSite_Section> lSections = ser.GetUserSectionsByUserId((Guid)mu.ProviderUserKey);

            int[] sectionIds = (from i in lSections
                                select i.ID).ToArray();

            GoogleWeatherData gwd = (this.Session["GoogleWeather"] != null) ? (GoogleWeatherData)this.Session["GoogleWeather"] : GoogleWeatherAPI.GetWeather(Animaonline.Globals.LanguageCode.fr_FR, ConfigurationManager.AppSettings["Weathe.City"]);
           
            List<sp_Site_GetNextMeetingsResult> lEvents = cr.GetNextEvents();
            List<sp_Site_GetNextMeetingsResult> lUserEvent = (from e in lEvents
                                                              where sectionIds.Contains(e.SID)
                                                              select e).ToList();

            ViewData["MailUrl"] = Url.Action("Agenda", new { controller = "Mail", systemName = systemName, mailId = mailId, userId = userId });
            
            if (lUserEvent != null && lUserEvent.Count > 0 && mu != null && mtg != null)
            {
                List<sp_Site_GetNextMeetingsResult> lNextEvents = cr.GetNextEventsFromDate(DateTime.Now.GetNowTimeByTimeZone().AddDays(7));
                List<sp_Site_GetNextMeetingsResult> lUserNextEvent = (from e in lNextEvents
                                                                      where sectionIds.Contains(e.SID)
                                                                      select e).ToList();

                List<tSite_Staff> lStaff = str.GetAllModeratorMembers();
                List<tSite_Convoc> lConvoc = cor.GetAllCurrentConvoc();
                List<ForecastCondition> lCondition = gwd.ForecastConditions.Skip(1).Take(3).ToList();

                //Data
                ViewData["PageTitle"] = Resources.Mail_Album_MailTitle;
                ViewData["CampaignName"] = this.Server.UrlEncode(Resources.Mail_Album_MailTitle);
                ViewData["SiteName"] = ConfigurationManager.AppSettings["SiteName"];
                ViewData["UserID"] = userId.ToString();
                ViewData["MailID"] = mtg.MID.ToString();
                ViewData["CopyrightDate"] = DateTime.Now.GetNowTimeByTimeZone().Year;
                ViewData["UserLogin"] = mu.UserName;
                ViewData["Conditions"] = lCondition;
                ViewData["Events"] = lUserEvent;
                ViewData["NextEvents"] = lUserNextEvent;
                ViewData["Staff"] = lStaff;
            }
            else 
            {
                string[] saBreadcrumb = new String[2];
                saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
                saBreadcrumb[1] = Resources.Mail_Agenda_Error_Breadcrumb;
                ViewData["Breadcrumb"] = saBreadcrumb;

                ViewData["PageTitle"] = Resources.Mail_Agenda_Error_Title;
                ViewData["ErrorMessage"] = Resources.Mail_Agenda_Error;
                if (this.ControllerContext.HttpContext.Request.Headers["ScheduleTask"] != null)
                {
                    this.ControllerContext.HttpContext.Response.StatusCode = 204;
                }
                return View("Error");
            }

            return View();
        }

        public ActionResult MembresAdminDelete(string systemName, int mailId, Guid userId)
        {
            ViewData["CopyrightDate"] = DateTime.Now.GetNowTimeByTimeZone().Year;
            ViewData["SiteName"] = ConfigurationManager.AppSettings["SiteName"];

            return View();
        }

        public ActionResult MembersAdminValidation(string systemName, Guid id)
        {
            MembershipUser mu = Membership.GetUser(id);

            if (mu != null)
            {
                ViewData["CopyrightDate"] = DateTime.Now.GetNowTimeByTimeZone().Year;
                ViewData["SiteName"] = ConfigurationManager.AppSettings["SiteName"];
                ViewData["UserLogin"] = mu.UserName.ToString().UppercaseFirst();
                ViewData["MailTitle"] = Resources.Mail_MembersAdminValidation_Title;
                ViewData["NoSignature"] = true;

                return View();
            }
            else
            {
                this.ControllerContext.HttpContext.Response.StatusCode = 204;

                return View("Error");
            }            
        }


        [HttpPost]
        public ActionResult ProfilAdminValidation(FormCollection fc)
        {
            ViewData["CopyrightDate"] = DateTime.Now.GetNowTimeByTimeZone().Year;
            ViewData["SiteName"] = ConfigurationManager.AppSettings["SiteName"];
            ViewData["MailTitle"] = Resources.Profil_Inscription_MailAdminValidation;

            ViewData["username"] = fc["username"];
            ViewData["firstname"] = fc["firstname"].UppercaseFirst();
            ViewData["lastname"] = fc["lastname"].UppercaseFirst();
            
            ViewData["NoSignature"] = true;

            return View();
        }

        [HttpPost]
        public ActionResult ProfilContributorValidation(FormCollection fc)
        {
            ViewData["username"] = fc["username"];
            ViewData["firstname"] = fc["firstname"];
            ViewData["lastname"] = fc["lastname"];
            ViewData["email"] = fc["email"];
            ViewData["password"] = fc["password"];

            ViewData["CopyrightDate"] = DateTime.Now.GetNowTimeByTimeZone().Year;
            ViewData["SiteName"] = ConfigurationManager.AppSettings["SiteName"];
            ViewData["MailTitle"] = Resources.Mail_ProfilUserValidation_MailValidationTitle;

            ViewData["NoSignature"] = true;

            return View();
        }

        [HttpPost]
        public ActionResult ProfilUserValidation(FormCollection fc)
        {
            ViewData["username"] = fc["username"];
            ViewData["firstname"] = fc["firstname"].UppercaseFirst();
            ViewData["lastname"] = fc["lastname"].UppercaseFirst();
            ViewData["email"] = fc["email"];
            ViewData["password"] = fc["password"];
            ViewData["URLValidation"] = ConfigurationManager.AppSettings["SiteUrl"] + "/Profil/ValidationUser/" + fc["UserID"];
            
            ViewData["CopyrightDate"] = DateTime.Now.GetNowTimeByTimeZone().Year;
            ViewData["SiteName"] = ConfigurationManager.AppSettings["SiteName"];
            ViewData["MailTitle"] = Resources.Mail_ProfilUserValidation_MailValidationTitle;

            ViewData["NoSignature"] = true;

            return View();
        }

        [HttpPost]
        public ActionResult Staff(FormCollection fc)
        {
            string siteName = ConfigurationManager.AppSettings["SiteName"];
            ViewData["SenderLastName"] = fc["SenderLastName"].UppercaseFirst();
            ViewData["SenderFirstName"] = fc["SenderFirstName"].UppercaseFirst();

            ViewData["CopyrightDate"] = DateTime.Now.GetNowTimeByTimeZone().Year;
            ViewData["SiteName"] = siteName;
            ViewData["MailTitle"] = Resources.Mail_Staff_MailStafTitle.Replace("[SITE_NAME]", siteName);

            ViewData["NoSignature"] = true;

            return View();
        }

        [HttpPost]
        public ActionResult Link(FormCollection fc)
        {
            ViewData["LinkTitle"] = fc["Title"];
            ViewData["LinkDescription"] = fc["Description"];
            ViewData["LinkURL"] = fc["URL"];

            ViewData["MailTitle"] = Resources.Mail_Link_MailTitle;
            ViewData["CopyrightDate"] = DateTime.Now.GetNowTimeByTimeZone().Year;
            ViewData["SiteName"] = ConfigurationManager.AppSettings["SiteName"];

            ViewData["NoSignature"] = true;

            return View();
        }

        [HttpPost]
        public ActionResult ForgotPassword(FormCollection fc)
        {
            Guid userID = new Guid(fc["UserID"]);
            MembershipUser mu = Membership.GetUser(userID);
            if (mu != null)
            {
                string password = mu.ResetPassword();

                ViewData["MailTitle"] = Resources.Mail_Forgot_MailTitle;

                ViewData["Password"] = password;
                ViewData["Email"] = mu.Email;
                ViewData["UserName"] = mu.UserName;

                ViewData["CopyrightDate"] = DateTime.Now.GetNowTimeByTimeZone().Year;
                ViewData["SiteName"] = ConfigurationManager.AppSettings["SiteName"];

                ViewData["NoSignature"] = true;
            }
            
            return View();
        }
    }
}